import MsgNotifyUtil from "@/utils/callcenter/base/MsgNotifyUtil";
import React from "react";


export function addFrameIfNotExsit(name, src) {
  let element1 = document.getElementsByName(name);
  if (element1.length == 0) {
    let frameElement = document.createElement("iframe");
    frameElement.title = "CallCenter";
    frameElement.width = "800px";
    frameElement.height = "800px";
    frameElement.name = name;
    frameElement.src = src;
    //frameElement.style = "display:block;position:absolute;z-index: 100;";
    frameElement.style = "display:none;";
    frameElement.allowusermedia = 'allowusermedia';
    frameElement.allow = "geolocation; microphone; camera; midi; encrypted-media;";
    document.getElementsByTagName("body")[0].appendChild(frameElement);
  }
}

/*

  发送消息 msgId用来保证会话
 */
export function executeFunctionFromIframe(context, funcName, data, func) {
  const msgId = MsgNotifyUtil.guid();
  if (func) {
    callCenterMsgNotifyUtil.addCallbackFunction(msgId, func);
  }
  context.postMessage({funcName: funcName, id: msgId, data: data, f: "c"}, '*');
}

//获取CallCenter提供的Frame
export function getCallCenterIframe(name) {
  let frames = window.frames;

  for (let i = 0; i < frames.length; i++) {
    const f = frames[i];
    if (f.name === name) {
      return f;
    }
  }

  return null;
}

//添加通知
const callCenterMsgNotifyUtil = new MsgNotifyUtil();
const frameListeners = {};

//暴露回调
export function addFrameListener(topic, handler) {
  frameListeners[topic] = handler;
}


//设置回收时间
callCenterMsgNotifyUtil.setRecycleTimeout(1000);
//监听RPC回调

window.top.addEventListener('message', function (e) {

  const {id, data, type} = e.data;
  if (type === "callback") {
    callCenterMsgNotifyUtil.notify(id, data);
  } else if (type === "notify") {
    const func = frameListeners[id];

    if (func != null) {
      func(data);
    }
  }
}, false);
